package appli.agentImpl;

import java.util.HashMap;
import java.util.Map;

import system.agent.Agent;
import system.util.message.Message;
import system.util.message.RequestMessage;
import system.util.message.ResponseMessage;

/**
 * A Directory is an agent who know all the open stores.
 */
public class Directory extends Agent {

	private static final long serialVersionUID = -5474604565209331073L;

	/**
	 * key : "Name" of the store (ex Carrefour)
	 * value : "Hostname:port" of the store (ex localhost:1000)
	 * A map of all known open stores
	 */
	private Map<String, String> stores;
	/**
	 * Address of the directory
	 */
	public static final String directoryAddressHost = "vmarc-laptop";
	/**
	 * Port of the directory
	 */
	public static final int directoryAddressPort = 1500;
	/**
	 * Name ofthe directory
	 */
	public static final String directoryName = "Pages Jaunes";
	
	public Directory() {
		super(Directory.directoryName, Directory.directoryAddressHost, Directory.directoryAddressPort);
		this.stores = new HashMap<String, String>();
	}

	public void addStore(String name, String hostName, int hostPort) {
		this.stores.put(name, hostName + ":" + hostPort);
	}

	public String getAddress(String name) {
		return this.stores.get(name);
	}

	public Map<String, String> getStores() {
		return this.stores;
	}

	@Override
	public void main() {
		Message m;
		while(true){
			// wait for incoming messages
			m = waitForNextMessage();
			// message traitment
			String[] msg = m.getMessage();
			if (msg[0].equals("REGISTERING")) {
				this.addStore(msg[1], msg[2], Integer.parseInt(msg[3]));
				if (OPTION) {
					System.out.println("Annuaire : Store \"" + msg[1] + "\" ajouté à la liste des magasins");
				}
			}
			else {
				if(msg[0].equals("GET")){
					if(msg[1].equals("STORES")){
						if(msg[2].equals("MAP")){
							ResponseMessage resp = ((RequestMessage)m).getFuture();
							resp.setData(new HashMap<String, String>(stores));
							resp.setMessage("SET" + Message.SEPARATOR + "STORES" + Message.SEPARATOR + "MAP");
						}
					}
				}
			}
		}
	}
}
